package top.firejames.util;

import org.junit.Test;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * @auther 夏浩
 * @creat 2021-09-2021/9/23-20:13
 */
public class FileUtil {

    public static Map<String, FileWriter> fileWriterMap = new HashMap<String, FileWriter>();


    /**
     * 实现对指定路径的写入（每次写入一行）
     *
     * @param path    文件路径
     * @param content 写入内容
     * @throws IOException
     */


    public static synchronized void write(String path, String content) throws IOException {
        FileWriter fileWriter = null;
        File file = new File(path);
        File parentFile = file.getParentFile();
        if (parentFile!=null) {
            parentFile.mkdir();
        }
        File absoluteFile = file.getAbsoluteFile();
        if (!fileWriterMap.containsKey(absoluteFile.getPath())) {
            fileWriter = new FileWriter(absoluteFile, true);
            fileWriterMap.put(absoluteFile.getPath(), fileWriter);
        }
        fileWriter = fileWriterMap.get(absoluteFile.getPath());
        fileWriter.write(content);
        String lastChar = content.substring(content.length() - 1);
        if (lastChar != "\n") {
            fileWriterMap.remove(absoluteFile.getPath());
            fileWriter.close();
        }
    }

    @Test
    public void test4() {

    }


//    public static void close(String path) throws IOException {
//        File file = new File(path);
//        File absoluteFile = file.getAbsoluteFile();
//        if (fileWriterMap.containsKey(absoluteFile.getPath())) {
//            fileWriterMap.get(absoluteFile.getPath()).close();
//        }
//    }

    /**
     * 实现从指定路径读入指定的行数并且写入到指定的路径中
     *
     * @param sourcePath 读文件地址
     * @param destPath   写入文件地址
     * @param startLine  开始读取行
     * @param endLine    读取结束行
     * @throws IOException
     */
    public static synchronized void LineNumberRead(String sourcePath, String destPath, int startLine, int endLine) throws IOException {
        FileReader fileReader = new FileReader(new File(sourcePath));
        LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
        int lineNumber = 0;
        String s = null;
        int count = 0;
        long allLines = Files.lines(Paths.get(sourcePath)).count();
        StringBuffer stringBuffer = new StringBuffer(1000);
        while ((s = lineNumberReader.readLine()) != null) {
            lineNumber = lineNumberReader.getLineNumber();
            if (lineNumber >= startLine && lineNumber <= allLines) {
                stringBuffer.append(s).append("\n");
                count++;
                if (count % 1000 == 0) {
                    if (lineNumber == endLine) {
                        stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
                    }
                    FileUtil.write(destPath, stringBuffer.toString());

                    stringBuffer.delete(0, stringBuffer.length());
                }
            }
            if ((lineNumber == endLine)) {
                break;
            }
        }
//        FileUtil.close(destPath);
        System.out.println("一共写入了" + count + "行");
        lineNumberReader.close();
        fileReader.close();
    }
//    @Test
//    public void  test8(){
//
//        StringBuffer stringBuffer = new StringBuffer();
//        stringBuffer.append(2389798).append("\n").append(2342973).append("\n");
//        FileUtil.write("txt\\0.txt",stringBuffer,true);
//
//
//    }

    @Test
    public void test1() {
        String s = "C:\\Users\\hpc\\Desktop\\107.txt";
        String source = "C:\\Users\\hpc\\Desktop\\104.txt";
        try {
            LineNumberRead(source, s, 0, 10000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param sourcePath
     * @return 返回文件中的数据，以数组的形式
     * @throws IOException
     */
    public static synchronized int[] LineNumberReadBySort(String sourcePath) throws IOException {
        System.out.println(sourcePath);
        File file = new File(sourcePath);
        FileReader fileReader = new FileReader(file);
        LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
        String str = null;
        LinkedList<Integer> list = new LinkedList<Integer>();

        StringBuffer allContent = new StringBuffer(100000);
        while ((str = lineNumberReader.readLine()) != null) {
            str.replaceAll("\n", "");
            str.replaceAll("\r", "");
            list.add(Integer.parseInt(str));
        }
        System.out.println("list" + list.size());

        int[] ints = list.stream().mapToInt(Integer::intValue).toArray();
        lineNumberReader.close();
        fileReader.close();
        file.delete();
        System.out.println("last   "+list.getLast());
        System.out.println("intsLast   " +ints[ints.length - 1]);
        return ints;
    }
}

//    @Test
//    public void test() {
//        char c = '2';
//        int i = Integer.parseInt(String.valueOf(c));
//        System.out.println(i);
//    }
//}
